<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="短剧ID" prop="platformId">
              <el-input v-model="queryParams.platformId" placeholder="请输入商品库ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oce:productStore:add']">
              {{ productIndustry === 'PLAYLET' ? '新增付费短剧' : productIndustry === 'IAAPLAYLET' ? '新增免费短剧' : '新增' }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oce:productStore:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oce:productStore:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:productStore:export']">导出</el-button>
          </el-col>
          <div class="flex items-center text-[12px] tips">
            <div class="ml-[10px] label">当前操作帐户：</div>
            <div class="val" :class="appStore.accountName ? 'text-[#409EFF]' : 'text-[#f00]'">{{ appStore.accountName || '未设置' }}</div>
          </div>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="dpaProductList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="开关" align="center" prop="status">
          <template #default="{ row }">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="短剧ID" align="center" prop="productId" />
        <el-table-column label="短剧名称" align="center" prop="name" />
        <el-table-column label="一级分类" align="center" prop="firstCategory" />
        <el-table-column label="二级分类" align="center" prop="subCategory" />
        <el-table-column label="三级分类" align="center" prop="thirdCategory" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oce:productStore:share']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oce:productStore:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改商品库对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="storeDetailsFormRef" :model="form" :rules="rules" label-width="auto" label-position="right">
        <el-form-item label="商品类目" prop="accountId">
          <el-cascader style="width: 100%" v-model="form.advertiserId" :options="options" @change="handleChange" />
        </el-form-item>
        <template v-if="productIndustry === 'PLAYLET'">
          <el-form-item prop="adCarrier">
            <template #label>
              <div style="display: flex; align-items: center">
                <span>投放载体</span>
                <el-tooltip class="box-item" effect="dark" content="请选择该短剧商品在广告投放中所绑定的全部投放载体" placement="top-start">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-checkbox-group v-model="form.profession.adCarrier" size="small">
              <template v-for="itm in groupList" :key="itm">
                <el-checkbox :label="itm.label" :value="itm.value" border />
              </template>
            </el-checkbox-group>
          </el-form-item>
        </template>
        <el-form-item label="字节小程序推广链接" prop="microAppLink" label-width="150px" v-if="form.profession.adCarrier.includes('1')">
          <el-input v-model="form.profession.microAppLink" placeholder="请输入字节小程序推广链接" />
        </el-form-item>
        <el-form-item
          label="短剧专辑链接"
          prop="albumLink"
          v-if="form.profession.adCarrier.includes('3') && !form.profession.adCarrier.filter((item) => item === '1').length > 0"
        >
          <el-input v-model="form.profession.albumLink" placeholder="请输入短剧专辑链接" />
        </el-form-item>
        <el-form-item label="剧目ID" prop="albumId" label-width="150px" v-if="form.profession.adCarrier.length > 0">
          <el-input v-model="form.profession.albumId" placeholder="请输入剧目ID" />
        </el-form-item>
        <el-form-item label="短剧名" prop="name">
          <el-input v-model="form.profession.name" placeholder="请输入短剧名" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="版权方主体名称" prop="copyrightOwner">
          <el-input v-model="form.profession.copyrightOwner" placeholder="请输入版权方主体名称" maxlength="25" show-word-limit />
        </el-form-item>
        <el-form-item label="短剧简介" prop="description">
          <el-input v-model="form.profession.description" placeholder="请输入短剧简介" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="playletGender">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>短剧男女频</span>
              <el-tooltip class="box-item" effect="dark" content="男频剧指更受男性偏好的短剧，女频剧指更受女性偏好的短剧" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-radio-group v-model="form.profession.playletGender" size="small">
            <el-radio-button label="男频" value="1" />
            <el-radio-button label="女频" value="2" />
            <el-radio-button label="其他" value="3" />
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="playletNum">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>剧类集数</span>
              <el-tooltip class="box-item" effect="dark" content="请填写该短剧共有多少集" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="form.profession.playletNum" placeholder="请输入剧类集数" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="变现模式" prop="hasPaidContent">
          <el-radio-group v-model="form.profession.hasPaidContent" size="small">
            <template v-if="productIndustry === 'PLAYLET'">
              <el-radio-button label="付费" value="1" />
              <el-radio-button label="混合" value="2" />
            </template>
            <template v-if="productIndustry === 'IAAPLAYLET'">
              <el-radio-button label="混合" value="1" />
              <el-radio-button label="免费" value="2" />
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否包含网赚内容" prop="hasMotivationContent">
          <el-radio-group v-model="form.profession.hasMotivationContent" size="small">
            <el-radio-button label="是" value="1" />
            <el-radio-button
              label="否"
              value="2"
              v-if="
                (productIndustry === 'IAAPLAYLET' && form.profession.hasPaidContent === '1') ||
                (productIndustry === 'PLAYLET' && form.profession.hasPaidContent === '2')
              "
            />
            <el-radio-button label="否" value="0" v-else />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员类型" prop="membershipTypes">
          <el-radio-group v-model="form.profession.membershipTypes" size="small">
            <el-radio-button label="终身" value="1" />
            <el-radio-button label="年度" value="2" />
            <el-radio-button label="月度" value="3" />
            <el-radio-button label="周/天" value="4" />
            <el-radio-button label="无" value="5" />
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="playletDuration">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>单集剧集时长(分钟)</span>
              <el-tooltip class="box-item" effect="dark" content="请填写短剧单集时长，单位为分钟，集数时长=总时长/总集数" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="form.profession.playletDuration" placeholder="请输入单集剧集时长(分钟)" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="startPayPlaylet">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>起始付费集数</span>
              <el-tooltip class="box-item" effect="dark" content="从第几集开始需要付费，仅支持填写数字" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="form.profession.startPayPlaylet" placeholder="请输入起始付费集数" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="price">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>单集价格（元，不含赠送）</span>
              <el-tooltip class="box-item" effect="dark" content="从第几集开始需要付费，仅支持填写数字" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="form.priceInfo.price" placeholder="请输入起始付费集数" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="maxCharge">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>最高充值档位(元)</span>
              <el-tooltip class="box-item" effect="dark" content="充值面板内的最高金额档位" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="form.profession.maxCharge" placeholder="请输入起始付费集数" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="minCharge">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>最低充值档位(元)</span>
              <el-tooltip class="box-item" effect="dark" content="充值面板内的最低金额档位" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="form.profession.minCharge" placeholder="请输入起始付费集数" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="recommendedCharge">
          <template #label>
            <div style="display: flex; align-items: center">
              <span>推荐充值档位(元)</span>
              <el-tooltip class="box-item" effect="dark" content="充值面板内的推荐金额档位" placement="top-start">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="form.profession.recommendedCharge" placeholder="请输入起始付费集数" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="imageUrl" label="商品图片">
          <NewImageUpload v-model="form.imageUrl" :accountId="appStore.accountId" :advertiserId="route.query.advertiserId" limit="1" />
        </el-form-item>
        <el-form-item prop="imageUrls" label="商品组图">
          <NewImageUpload v-model="form.imageUrls" :accountId="appStore.accountId" :advertiserId="route.query.advertiserId" limit="1" />
        </el-form-item>
        <el-form-item label="商品落地页" prop="targetUrl">
          <el-input v-model="form.landingInfo.targetUrl" placeholder="请输入链接地址" maxlength="25" show-word-limit />
        </el-form-item>
        <el-form-item label="商品H5落地页" prop="targetUrlMobile">
          <el-input v-model="form.landingInfo.targetUrlMobile" placeholder="请输入链接地址" maxlength="25" show-word-limit />
        </el-form-item>
        <el-form-item label="商品安卓落地页" prop="targetUrlAndroidApp">
          <el-input v-model="form.landingInfo.targetUrlAndroidApp" placeholder="请输入链接地址" maxlength="25" show-word-limit />
        </el-form-item>
        <el-form-item label="商品IOS落地页" prop="targetUrlAndroidApp">
          <el-input v-model="form.landingInfo.targetUrlIosApp" placeholder="请输入链接地址" maxlength="25" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductStore" lang="ts">
// import {getdpaProductList, syncProductStore} from '@/api/advertisement/productStore';
import { getDpaProductList, addDpaProduct } from '@/api/advertisement/details';
import { ProductStoreVo, ProductStoreQuery } from '@/api/advertisement/productStore/types';

import { useAppStore } from '@/store/modules/app';
const appStore = useAppStore();
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dpaProductList = ref<ProductStoreVo[]>([]);
const productIndustry = ref(); // 商品库行业类别,免费IAAPLAYLET， 付费PLAYLET
const groupList = ref([
  {
    label: '字节小程序',
    value: '1'
  },
  {
    label: '微信小程序',
    value: '2'
  },
  {
    label: '端原生组件',
    value: '3'
  },
  {
    label: '安卓/IOS应用',
    value: '4'
  }
]);
const options = ref([
  {
    value: 'guide',
    label: 'Guide',
    children: [
      {
        value: 'disciplines',
        label: 'Disciplines',
        children: [
          {
            value: 'consistency',
            label: 'Consistency'
          },
          {
            value: 'feedback',
            label: 'Feedback'
          },
          {
            value: 'efficiency',
            label: 'Efficiency'
          },
          {
            value: 'controllability',
            label: 'Controllability'
          }
        ]
      },
    ]
  }
]);
const checkboxGroup1 = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const storeDetailsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProductStoreForm = {
  profession: {
    adCarrier: [],
    microAppLink: undefined,
    albumId: undefined,
    albumLink: undefined,
    name: undefined,
    copyrightOwner: undefined,
    description: undefined,
    playletGender: [],
    playletNum: undefined,
    hasPaidContent: undefined,
    hasMotivationContent: undefined,
    membershipTypes: undefined,
    playletDuration: undefined,
    startPayPlaylet: undefined,
    maxCharge: undefined,
    minCharge: undefined,
    recommendedCharge: undefined
  },
  priceInfo: {
    price: undefined
  },
  landingInfo: {
    targetUrl: undefined,
    targetUrlMobile: undefined,
    targetUrlAndroidApp: undefined,
    targetUrlIosApp: undefined
  },
  imageUrl: undefined,
  imageUrls: undefined,

  platformId: undefined,
  accountId: undefined,
  advertiserId: undefined,
  firstCategory: undefined, // 一级分类
  firstCategoryId: undefined, // 一级分类id
  subCategory: undefined, // 二级分类
  subCategoryId: undefined, // 二级分类id
  thirdCategory: undefined, // 三级分类
  thirdCategoryId: undefined // 三级分类id
  // name: undefined,
  // productIndustry: undefined
};
const data = reactive<PageData<ProductStoreForm, ProductStoreQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    advertiserId: undefined,
    productPlatformId: undefined,
    name: undefined,
    productIndustry: undefined,
    params: {}
  },
  rules: {
    checkboxGroup1: [{ required: true, message: '投放载体不能为空', trigger: 'blur' }],
    platformId: [{ required: true, message: '商品库ID不能为空', trigger: 'blur' }],
    accountId: [{ required: true, message: '管家账号id不能为空', trigger: 'blur' }],
    advertiserId: [{ required: true, message: '广告主id不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '商品库名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
//
const handleStatusChange = async (row: ProductStoreVO) => {
  const text = row.status === '0' ? '启用' : '停用';
  // await updateStatus(row.platformId as string, row.status);
  // proxy?.$modal.msgSuccess(`${text}成功`);
};
watch(
  () => route.query,
  () => {
    productIndustry.value = route.query.productIndustry as string;
  }
);
onActivated(() => {
  getList();
});
const handleChange = (value) => {
  console.log(value);
};
/** 查询商品库列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.advertiserId = route.query.advertiserId as string;
  queryParams.value.productPlatformId = route.query.platformId as string;
  const res = await getDpaProductList(queryParams.value);
  dpaProductList.value = res.data;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  storeDetailsFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductStoreVO[]) => {
  ids.value = selection.map((item) => item.platformId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = productIndustry.value === 'PLAYLET' ? '添加付费短剧' : productIndustry.value === 'IAAPLAYLET' ? '添加免费短剧' : '添加';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProductStoreVO) => {
  reset();
  const _platformId = row?.platformId || ids.value[0];
  const res = await getProductStore(_platformId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改商品库';
};

/** 提交按钮 */
const submitForm = () => {
  form.value.productIndustry = productIndustry.value;
  storeDetailsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.platformId) {
        // await updateProductStore(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDpaProduct(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProductStoreVO) => {
  const _platformIds = row?.platformId || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品库编号为"' + _platformIds + '"的数据项？').finally(() => (loading.value = false));
  await delProductStore(_platformIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oce/productStore/export',
    {
      ...queryParams.value
    },
    `productStore_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  productIndustry.value = route.query.productIndustry as string;
});
</script>
